What is fb-watchman?
The fb-watchman npm package is a file watching service developed by Facebook that provides a subscription-based API for monitoring file changes. It is designed to be efficient and scales well for large file systems, making it suitable for applications that need to keep track of changes in the file system in real-time.
Subscribe to file changes
This code sample demonstrates how to use fb-watchman to subscribe to changes in JavaScript files within a specified project directory. It sets up a watch, creates a subscription, and logs any changes to the console.
const watchman = require('fb-watchman');
const client = new watchman.Client();
client.capabilityCheck({optional:[], required:['relative_root']}, function(error, resp) {
if (error) {
console.error(error);
client.end();
return;
}
// Initiate the watch
client.command(['watch-project', '/path/to/project'], function(error, resp) {
if (error) {
console.error('Error initiating watch:', error);
return;
}
// Create a subscription
client.command(['subscribe', resp.watch, 'mysubscription', {
expression: ['allof', ['match', '*.js']],
fields: ['name', 'size', 'mtime_ms', 'exists', 'type']
}], function(error, resp) {
if (error) {
console.error('Error creating subscription:', error);
return;
}
console.log('Subscription established', resp.subscribe);
});
});
});
client.on('subscription', function(resp) {
if (resp.subscription === 'mysubscription') {
console.log('File changed:', resp);
}
});